﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;
using Microsoft.SharePoint.WebControls;

using PortalFileUrls = Kiiro.Common.Utility.Constants.PortalFileUrls;
using ProjectFileUrls = Kiiro.Common.Utility.Constants.ProjectFileUrls;
using Microsoft.SharePoint.Utilities;
using Kiiro.SiteDefinition.MasterPage;

namespace Kiiro.SiteDefinition.ProjectPages
{
    public partial class DisplayIssue : BasePage
    {
        private List<TeamMember> projectTeamMembers;
        public List<TeamMember> ProjectTeamMembers
        {
            get { return projectTeamMembers; }
            set { projectTeamMembers = value; }
        }

        private Work work;
        public Work Work
        {
            get { return work == null ? new Work ( ) : work; }
            set { work = value; }
        }

        public CustomFieldCollection CustomFields
        {
            get { return ( CustomFieldCollection ) v2CustomFieldCollection; }
        }

        public TeamMemberCollection TeamMembers
        {
            get { return ( TeamMemberCollection ) teamMemberList; }
        }

        public AttachmentControl Attachments
        {
            get { return ( AttachmentControl ) attachmentControl; }
        }

        public double HoursPerDay
        {
            get { return SetupModel.GetHoursPerDay ( SiteCollectionId, ServerRelativeUrl ); }
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            TeamMembers.PageMode = PageMode.Display;
            Attachments.ControlMode = PageMode.Display;
            CustomFields.ControlMode = SPControlMode.Display;
            CustomFields.EntityType = typeof ( Work );
            CustomFields.Title = "Additional Information";

            litTitle.Text = "Display Issue";
            if ( KiiroMaster.V2Header.Project != null && !string.IsNullOrEmpty ( KiiroMaster.V2Header.Project.Title ) )
            {
                litTitle.Text = KiiroMaster.V2Header.Project.Title + " - Display Issue";
            }

            if ( ItemId > 0 )
            {
                Work = WorkModel.GetById ( ItemId, SiteCollectionId, ServerRelativeUrl );

                if ( Work != null )
                {
                    litTitle.Text = litTitle.Text + " - " + work.Title;
                    // override page permissions and get object level permissions
                    PermissionsModel.GetGlobalPermissionBitsForCurrentUser ( Work, CurrentUser, SiteCollectionId, ServerRelativeUrl );

                    if ( Work.PermissionBitsWork != null && Work.PermissionBitsWork.Count > 0 )
                    {
                        btnDeleteIssue.Attributes.Add ( "onclick", "return confirm('Are you sure you wish to delete this issue?')" );

                        ProjectTeamMembers = TeamModel.GetTeamMembers ( SiteCollectionId, ServerRelativeUrl );

                        if ( !Page.IsPostBack )
                        {
                            PopulateForm ( );
                        }
                    }
                    else
                    {
                        Redirect ( string.Empty );
                    }
                }
                else
                {
                    Redirect ( string.Empty );
                }
            }
            else
            {
                Redirect ( string.Empty );
            }
        }

        /// <summary>
        /// Populate the form fields with retrieved data
        /// </summary>
        private void PopulateForm ( )
        {
            PopulateActionBar ( );

            lblTitle.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( Work.Title );
            lblIsHighPriority.Text = Work.IsHighPriority ? "Yes" : "No";
            lblAssignedWork.Text = FormattingHelpers.ConvertFromMinutes ( Work.AssignedWork, KiiroMaster.V2Header.Project.TimeMetric, HoursPerDay ).ToString ( );
            lblDescription.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( Work.Description );
            if ( work.EndDate != null && work.EndDate != DateTime.MinValue )
                lblEndDate.Text = FormattingHelpers.DateTimeToDatePickerString ( Work.EndDate );

            TeamMembers.TeamMembers = ProjectTeamMembers;
            TeamMembers.SelectedIds = Work.AssignedToList;

            hidWorkItemId.Value = Work.Id.ToString ( );
            txtStatusMessage.Text = Work.StatusNote;
            rblIssueStatus.SelectedValue = ( ( int ) Work.Status ).ToString ( );


            if ( KiiroMaster.V2Header.Project != null )
            {
                lblTimeUnit.Text = KiiroMaster.V2Header.Project.TimeMetric.ToString ( );
            }

            // set control mode to display before calling SetAttachments (default is edit mode)
            if ( Work.AttachmentList != null && Work.AttachmentList.Count > 0 )
            {
                Attachments.SetAttachments ( Work.AttachmentList );
            }
            else
            {
                pnlAttachmentSettings.Visible = false;
            }
        }

        private void PopulateActionBar ( )
        {
            if ( Request.UrlReferrer != null )
            {
                if ( Request.UrlReferrer.OriginalString.ToLower ( ).Contains ( Constants.PortalFileUrls.WorkOnAllProjects.ToLower ( ) ) )
                {
                    lnkBack.NavigateUrl = String.Format ( "{0}{1}", SPHelpers.GetPortalServerRelativeUrl ( SiteCollectionId, ServerRelativeUrl ), PortalFileUrls.WorkOnAllProjects );
                    lnkBack.Text = "Back to My Work On Projects";
                }
                else if ( Request.UrlReferrer.OriginalString.Contains ( Constants.ProjectFileUrls.WorkAll ) )
                {
                    lnkBack.NavigateUrl = ServerRelativeUrl + Constants.ProjectFileUrls.WorkAll;
                    lnkBack.Text = "Back to All Work";
                }
                else if ( Request.UrlReferrer.OriginalString.ToLower ( ).Contains ( Constants.ProjectFileUrls.ProjectSummary.ToLower ( ) ) )
                {
                    lnkBack.NavigateUrl = Request.UrlReferrer.OriginalString;
                    lnkBack.Text = "Back to Summary Page";
                }
                else if ( Request.UrlReferrer.OriginalString.ToLower ( ).Contains ( Constants.PortalFileUrls.PortalActivity.ToLower ( ) ) )
                {
                    lnkBack.NavigateUrl = Request.UrlReferrer.OriginalString;
                    lnkBack.Text = "Back to Recent Activity Page";
                }
                else if ( Request.UrlReferrer.OriginalString.ToLower ( ).Contains ( Constants.PortalFileUrls.SearchResults.ToLower ( ) ) )
                {
                    lnkBack.NavigateUrl = Request.UrlReferrer.OriginalString;
                    lnkBack.Text = "Back to Search Page";
                }
                else
                {
                    lnkBack.NavigateUrl = ServerRelativeUrl + Constants.ProjectFileUrls.MyWork;
                    lnkBack.Text = "Back to My Work";
                }
            }
            else
            {
                lnkBack.NavigateUrl = ServerRelativeUrl + Constants.ProjectFileUrls.MyWork;
                lnkBack.Text = "Back to My Work";
            }
        }

        protected void btnNewIssue_Click ( object sender, EventArgs e )
        {
            if ( Work.PermissionBitsWork [ 0 ] )
                Response.Redirect ( String.Format ( "{0}{1}", ServerRelativeUrl, ProjectFileUrls.IssueNew ) );
        }

        protected void btnEditIssue_Click ( object sender, EventArgs e )
        {
            if ( Work.PermissionBitsWork [ 2 ] )
                Response.Redirect ( String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, ProjectFileUrls.IssueEdit, ItemId ) );
        }

        protected void btnDeleteIssue_Click ( object sender, EventArgs e )
        {
            if ( Work.PermissionBitsWork [ 3 ] )
            {
                Work.EditType = EditType.Deleted;
                Work.ModifiedBy = CurrentUser;
                WorkModel.Save ( Work, SiteCollectionId, ServerRelativeUrl );
                Redirect ( string.Empty );
            }
        }

        private void Redirect ( string redirectUrl )
        {
            string url = default ( string );

            url = ServerRelativeUrl + ProjectFileUrls.MyWork;

            if ( !string.IsNullOrEmpty ( redirectUrl ) )
            {
                url = redirectUrl;
            }

            Response.Redirect ( url );
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.ProjectPages/Work/DisplayIssue.aspx.cs $
 * 
 * 13    10/26/09 9:41a Adamw
 * 
 * 12    10/23/09 6:13p Adamw
 * Case 348
 * 
 * 11    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 10    30/09/09 9:56a Shafia
 * 
 * 9     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/